from DrissionPage import ChromiumPage, ChromiumOptions
import time
from fake_useragent import UserAgent
ua = UserAgent()
random_user_agent = ua.random
from loguru import logger
import random


def random_move_and_click(co, str_xpath):
    # 随机移动鼠标
    for _ in range(1):  # 执行次数随机移动
        offset_x = random.randint(-100, 100)
        offset_y = random.randint(-100, 100)
        duration = random.uniform(0.1, 0.3)
        co.actions.move(offset_x, offset_y, duration)
        time.sleep(random.uniform(0.1, 0.2))  # 每次移动后短暂停顿
    web_page_elements = ['x://*[@id="onetrust-banner-sdk"]/div/div[1]/div', 'x://*[@id="main"]/div[3]/ol', 'x://*[@id="main"]/div[3]/div', 'x://*[@id="navbarReact"]/div/div/div/div[4]/div']
    # 移动到指定元素并点击
    co.actions.move_to(f'{str_xpath}').click()
    co.actions.move_to(random.choice(web_page_elements)).click()

def get_abck():
    retry_count = 0
    logger.info(f"启动浏览器获取_abck")
    while retry_count < 3:
        co = ChromiumOptions().no_imgs(False).new_env()
        # co.set_argument('--incognito') # 无痕
        # co.set_argument('--user-agent', f'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36')
        co.set_argument('--user-agent', random_user_agent)
        co.headless() # 无头模式
        co = ChromiumPage(co)
        co.get(r'https://www.zimchina.com/schedules/point-to-point')
        logger.info(f"点击获取中")
        random_move_and_click(co=co, str_xpath=r'x://*[@id="main"]/div[3]/div/h1')
        cookies = co.cookies()
        abck_cookie = next((cookie for cookie in cookies if cookie['name'] == '_abck'), None)
        # co.close()  # 关闭浏览器
        if abck_cookie:
            sys = abck_cookie['value'].split('~')[1]
            if str(sys) == '0':
                logger.success(f"有效_abck: {abck_cookie['value']}")
                return abck_cookie['value']
            else:
                logger.error(f"无效_abck参数")
                retry_count += 1
        else:
            print("_abck cookie not found")
            retry_count += 1
        if retry_count == 3:
            logger.error(f"获取_abck失败已达 {retry_count} 次")
            return 0

# get_abck()